package com.superdaxue.rxsampledemo.utils;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.CookieManager;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

/**
 * @author C.C
 * @date 2016年3月24日 下午6:42:59
 * @version 1.0 
 * 事件监听回调接口可根据需求自由改动 在 Manifest文件中 WebView所在Activity节点下加入
 *          android:hardwareAccelerated="true" 硬件加速
 *          android:process="packagename.web" 开启异步线程
 */
@SuppressWarnings("deprecation")
public class WebViewUtils {
	private View rl_web;
	private WebView wv;
	private WebViewLoadCallBack webViewCallBack;
    private Activity context;
	public WebViewUtils(Activity context, Bundle savedInstanceState, String url) {
		this.context = context;
		webViewCallBack = (WebViewLoadCallBack) context;
		rl_web = ((ViewGroup) context.findViewById(android.R.id.content)).getChildAt(0);
		initView(context, savedInstanceState, url);
	}

	private void initView(Context context, Bundle savedInstanceState, String url) {
		wv = new WebView(context.getApplicationContext());
		WebSettings webSettings = wv.getSettings();
		webSettings.setLoadWithOverviewMode(true); // 自适应屏幕
		webSettings.setSupportZoom(true); // 设定支持缩放
		webSettings.setLoadsImagesAutomatically(true);
		webSettings.setBlockNetworkImage(false);
		webSettings.setAppCacheEnabled(true);
		webSettings.setJavaScriptEnabled(true);
		webSettings.setBuiltInZoomControls(true);
		webSettings.setDisplayZoomControls(true);
		// 设置 缓存模式
		webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
		// 开启 DOM storage API 功能
		webSettings.setDomStorageEnabled(true);
		((ViewGroup) rl_web).addView(wv);
		if (savedInstanceState != null) {
			wv.restoreState(savedInstanceState);
		} else {
			wv.loadUrl(url);
		}
		wv.setWebChromeClient(new WebChromeClient() {
			@Override
			public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
				wv.loadUrl(url);
				return true;
			}
		});
		wv.setWebViewClient(new WebViewClient() {
			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				wv.loadUrl(url);
				return true;
			}

			@Override
			public void onPageStarted(WebView view, String url, Bitmap favicon) {
				super.onPageStarted(view, url, favicon);
				webViewCallBack.onUtilPageStarted(view, url, favicon);
			}

			@Override
			public void onPageFinished(WebView view, String url) {
				super.onPageFinished(view, url);
				webViewCallBack.onUtilPageFinished(view, url);
			}

			@Override
			public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
				super.onReceivedError(view, errorCode, description, failingUrl);
				webViewCallBack.onUtilReceivedError(view, errorCode, description, failingUrl);
			}
		});
	}

	/**
	 * 回退
	 */
	public boolean onBackPressed() {
		if (wv != null && wv.canGoBack()) {
			wv.goBack();
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 保存状态
	 * 
	 * @param outState
	 */
	public void saveState(Bundle outState) {
		if (wv != null) {
			wv.saveState(outState);
		}
	}

	@SuppressWarnings("deprecation")
	public void release() {
		if (wv != null && rl_web != null) {
			wv.stopLoading();
			wv.clearCache(true);
			wv.clearHistory();
			CookieManager cookieManager = CookieManager.getInstance();
			cookieManager.setAcceptCookie(true);
			if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
				cookieManager.removeAllCookie();
			}else {
				cookieManager.removeAllCookies(new ValueCallback<Boolean>() {
					@Override
					public void onReceiveValue(Boolean value) {
						if (value) {
							Log.e("webview", "--清除cookie");
						}
					}
				});
			}
			((ViewGroup) rl_web).removeAllViews();
			wv.destroy();
			wv = null;
			rl_web = null;
		}
	}

	public interface WebViewListenerCallBack {
	}

	public interface WebViewLoadCallBack {
		public void onUtilPageStarted(WebView view, String url, Bitmap favicon);

		public void onUtilPageFinished(WebView view, String url);

		public void onUtilReceivedError(WebView view, int errorCode, String description, String failingUrl);
	}
}
